package com.itheima.health.service.impl;

import com.itheima.health.dao.UserDao;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    /**
     * 用户注册
     * @param registerUser 用户名,密码,手机号
     * @return 统一结果
     */
    @Override
    public Result register(User registerUser) {
        // 调用DAO查看用户名是否被注册
        User queryUser = userDao.findByUsername(registerUser.getUsername());
        if (queryUser != null) {
            return new Result(false, "注册失败, 用户名已被注册");
        }

        // 调用DAO查看查看手机号是否被注册
        queryUser = userDao.findByTelephone(registerUser.getTelephone());
        if (queryUser != null) {
            return new Result(false, "注册失败, 手机号已被注册!");
        }

        // 给密码加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String bcryptPassword = encoder.encode(registerUser.getPassword());
        registerUser.setPassword(bcryptPassword);

        // 调用DAO把用户数据添加到数据库
        userDao.register(registerUser);

        return new Result(true, "注册成功");
    }

    @Override
    public Result login(User loginUser) {
        // 调用DAO通过用户名查询用户
        User queryUser = userDao.findByUsername(loginUser.getUsername());
        if (queryUser == null) {
            return new Result(false, "登录失败, 用户名不存在!");
        }

        // 用户名找到用户,对比密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean matches = encoder.matches(loginUser.getPassword(), queryUser.getPassword());
        System.out.println("matches = " + matches);
        if (matches) {
            return new Result(true, "登录成功");
        } else {
            return new Result(false, "登录失败, 密码错误!");
        }
    }

    /**
     * 通过手机号查询用户
     * @param telephone 手机号
     * @return
     */
    @Override
    public User findByTelephone(String telephone) {
        // 调用DAO通过用户名查询用户
        User queryUser = userDao.findByTelephone(telephone);
        // 返回查询到的用户
        return queryUser;
    }

}
